extends Node

@export var item_scene: PackedScene
@export var ball_scene: PackedScene

var score: int = 0
var balls_count: int = 0

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	$Paddle.hide()

func new_game() -> void:
	score = 0
	$StartTimer.start()
	
	$HUD.update_score(str(score))
	$HUD.show_message("Get Ready!")

func _on_ball_leaved() -> void:
	balls_count -= 1
	print("ball leaved, ball count ", balls_count)
	if balls_count <= 0:
		balls_count = 0
		print("start to end game")
		game_over()
	
func game_over() -> void:
	$ItemTimer.stop()
	$HUD.show_game_over()
	$Paddle.hide()
	get_tree().call_group("item", "queue_free")

func _on_item_timer_timeout() -> void:
	var item = item_scene.instantiate()
	
	var item_spawn_location = $ItemPath/ItemSpawnLocation
	item_spawn_location.progress_ratio = randf()
	item.position = item_spawn_location.position
	
	item.add_to_group("item")
	
	add_child(item)


func _on_hub_start_game() -> void:
	new_game()

func _on_ball_hit() -> void:
	score += 1
	$HUD.update_score(str(score))

func _on_start_timer_timeout() -> void:
	$ItemTimer.start()
	new_ball($StartPosition.position)
	$Paddle.reset()
	$Paddle.show()

func new_ball(ball_position: Vector2) -> void:
	var ball = ball_scene.instantiate()
	ball.start(ball_position)
	add_child(ball)
	balls_count += 1
	ball.connect("hit", self._on_ball_hit)
	ball.connect("leaved", self._on_ball_leaved)
